import { NativeModules } from 'react-native';
import { Card, CreateCardRequest, UpdateCardRequest } from '../types/Card';

const { CardApiModule } = NativeModules;

// 缓存配置
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟
const MAX_RETRY_COUNT = 3;
const RETRY_DELAY = 1000; // 1秒

// 缓存存储
const cache = new Map<string, { data: any; timestamp: number }>();

// 工具函数
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

const getCachedData = (key: string): any | null => {
  const cached = cache.get(key);
  if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
    return cached.data;
  }
  return null;
};

const setCachedData = (key: string, data: any) => {
  cache.set(key, { data, timestamp: Date.now() });
};

const clearCache = () => {
  cache.clear();
};

// 重试函数
const retryOperation = async <T>(
  operation: () => Promise<T>,
  maxRetries: number = MAX_RETRY_COUNT
): Promise<T> => {
  let lastError: Error;
  
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error));
      console.warn(`操作失败 (第 ${attempt} 次):`, lastError.message);
      
      if (attempt < maxRetries) {
        await sleep(RETRY_DELAY * attempt); // 指数退避
      }
    }
  }
  
  throw lastError!;
};

class CardApiNative {
  private static serverStarted = false;

  /**
   * 启动 API 服务器
   */
  static async startApiServer(): Promise<boolean> {
    if (this.serverStarted) {
      console.log('API 服务器已经启动');
      return true;
    }

    try {
      console.log('启动 API 服务器...');
      await retryOperation(async () => {
      await CardApiModule.startApiServer();
      });
      
      this.serverStarted = true;
      console.log('✅ API 服务器启动成功');
      return true;
    } catch (error) {
      console.error('❌ 启动 API 服务器失败:', error);
      throw error;
    }
  }

  /**
   * 获取卡片列表
   */
  static async getCards(): Promise<Card[]> {
    const cacheKey = 'cards_list';
    
    // 检查缓存
    const cachedData = getCachedData(cacheKey);
    if (cachedData) {
      console.log('📦 使用缓存的卡片列表');
      return cachedData;
    }

    try {
      console.log('通过 NativeModule 获取卡片列表...');
      
      const response = await retryOperation(async () => {
        return await CardApiModule.getCards();
      });
      
      const data = JSON.parse(response);
      console.log('卡片列表获取成功:', data);
      
      const cards = data.data || [];
      
      // 缓存结果
      setCachedData(cacheKey, cards);
      
      return cards;
    } catch (error) {
      console.error('获取卡片列表失败:', error);
      throw error;
    }
  }

  /**
   * 创建卡片
   */
  static async createCard(cardData: CreateCardRequest): Promise<Card> {
    try {
      console.log('CardApiNative.createCard 收到参数:', cardData);
      const jsonStr = JSON.stringify(cardData);
      console.log('CardApiNative.createCard 发送 JSON 字符串:', jsonStr);
      
      const response = await retryOperation(async () => {
        return await CardApiModule.createCard(jsonStr);
      });
      
      console.log('NativeModule 原始响应:', response);
      console.log('响应类型:', typeof response);
      
      const data = JSON.parse(response);
      console.log('解析后的响应数据:', data);
      console.log('响应数据结构:', {
        code: data.code,
        dataType: typeof data.data,
        dataKeys: data.data ? Object.keys(data.data) : 'null'
      });
      
      if (data.code !== 0) {
        console.error('❌ 服务器返回错误:', data);
        throw new Error(`服务器错误: ${data.data}`);
      }
      
      console.log('卡片创建成功:', data);
      
      // 清除卡片列表缓存
      cache.delete('cards_list');
      
      return data.data;
    } catch (error) {
      console.error('创建卡片失败:', error);
      throw error;
    }
  }

  /**
   * 更新卡片
   */
  static async updateCard(id: number, cardData: UpdateCardRequest): Promise<Card> {
    try {
      console.log('通过 NativeModule 更新卡片...');
      console.log('卡片ID:', id);
      console.log('发送的卡片数据:', JSON.stringify(cardData, null, 2));
      
      const response = await retryOperation(async () => {
        return await CardApiModule.updateCard(id, JSON.stringify(cardData));
      });
      
      console.log('NativeModule 原始响应:', response);
      console.log('响应类型:', typeof response);
      
      const data = JSON.parse(response);
      console.log('解析后的响应数据:', data);
      console.log('响应数据结构:', {
        code: data.code,
        dataType: typeof data.data,
        dataKeys: data.data ? Object.keys(data.data) : 'null'
      });
      
      if (data.code !== 0) {
        console.error('❌ 服务器返回错误:', data);
        throw new Error(`服务器错误: ${data.data}`);
      }
      
      console.log('卡片更新成功:', data);
      
      // 清除卡片列表缓存
      cache.delete('cards_list');
      
      return data.data;
    } catch (error) {
      console.error('更新卡片失败:', error);
      throw error;
    }
  }

  /**
   * 删除卡片
   */
  static async deleteCard(id: number): Promise<void> {
    try {
      console.log('通过 NativeModule 删除卡片...');
      
      await retryOperation(async () => {
      await CardApiModule.deleteCard(id);
      });
      
      console.log('卡片删除成功');
      
      // 清除卡片列表缓存
      cache.delete('cards_list');
    } catch (error) {
      console.error('删除卡片失败:', error);
      throw error;
    }
  }

  /**
   * 获取本机局域网 IP 地址
   */
  static async getLocalIPAddress(): Promise<string> {
    const cacheKey = 'local_ip';
    
    // 检查缓存
    const cachedIP = getCachedData(cacheKey);
    if (cachedIP) {
      console.log('📦 使用缓存的 IP 地址:', cachedIP);
      return cachedIP;
    }

    try {
      console.log('通过 NativeModule 获取本机局域网 IP...');
      
      const ip = await retryOperation(async () => {
        return await CardApiModule.getLocalIPAddress();
      });
      
      console.log('本机局域网 IP 获取成功:', ip);
      
      // 缓存 IP 地址（缓存时间稍长一些）
      setCachedData(cacheKey, ip);
      
      return ip;
    } catch (error) {
      console.error('获取本机局域网 IP 失败:', error);
      throw error;
    }
  }

  /**
   * 清除所有缓存
   */
  static clearCache(): void {
    clearCache();
    console.log('🗑️ 缓存已清除');
  }

  /**
   * 获取缓存统计信息
   */
  static getCacheStats(): { size: number; keys: string[] } {
    return {
      size: cache.size,
      keys: Array.from(cache.keys()),
    };
  }

  /**
   * 检查服务器状态
   */
  static isServerStarted(): boolean {
    return this.serverStarted;
  }

  /**
   * 发送UDP广播
   */
  static async sendUDPBroadcast(): Promise<string> {
    try {
      console.log('开始发送UDP广播...');
      
      const response = await retryOperation(async () => {
        return await CardApiModule.sendUDPBroadcast();
      });
      
      console.log('✅ UDP广播发送成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 发送UDP广播失败:', error);
      throw error;
    }
  }

  /**
   * 获取设备型号
   */
  static async getDeviceModel(): Promise<string> {
    try {
      console.log('获取设备型号...');
      
      const model = await retryOperation(async () => {
        return await CardApiModule.getDeviceModel();
      });
      
      console.log('✅ 设备型号获取成功:', model);
      return model;
    } catch (error) {
      console.error('❌ 获取设备型号失败:', error);
      throw error;
    }
  }

  /**
   * 获取设备名称
   */
  static async getDeviceName(): Promise<string> {
    try {
      console.log('获取设备名称...');
      
      const response = await retryOperation(async () => {
        return await CardApiModule.getDeviceName();
      });
      
      // 解析响应获取设备名称
      const responseData = JSON.parse(response);
      const deviceName = responseData.data?.name || '未知设备';
      
      console.log('✅ 设备名称获取成功:', deviceName);
      return deviceName;
    } catch (error) {
      console.error('❌ 获取设备名称失败:', error);
      throw error;
    }
  }

  /**
   * 设置设备名称
   */
  static async setDeviceName(name: string): Promise<string> {
    try {
      console.log('设置设备名称:', name);
      
      const response = await retryOperation(async () => {
        return await CardApiModule.setDeviceName(name);
      });
      
      console.log('✅ 设备名称设置成功:', response);
      return response;
    } catch (error) {
      console.error('❌ 设置设备名称失败:', error);
      throw error;
    }
  }
}

export default CardApiNative; 